package com.hkts.flow.core.flowable.listener.global;

import com.hkts.flow.feign.FeignInterface;
import com.hkts.flow.interceptor.FlowAbleInterceptor;
import com.hkts.flow.manager.utils.Result;
import org.flowable.bpmn.model.*;
import org.flowable.bpmn.model.Process;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.impl.event.FlowableEntityEventImpl;
import org.flowable.engine.*;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.impl.util.ProcessDefinitionUtil;
import org.flowable.engine.runtime.Execution;
import org.flowable.identitylink.api.IdentityLink;
import org.flowable.task.api.Task;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Description: 全局的任务创建监听
 * @Author: Bruce.liu
 * @Since:19:15 2019/12/13
 *  2018 ~ 2030 版权所有
 */
@Component
public class GlobalTaskCreateListener extends AbstractFlowableEngineEventListener {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    protected RuntimeService runtimeService;
    @Autowired
    protected HistoryService historyService;
    @Autowired
    protected RepositoryService repositoryService;
    @Autowired
    protected TaskService taskService;
    @Autowired
    protected IdentityService identityService;
    @Autowired
    RestTemplate restTemplate;
    @Value("${performance.address}")
    private String address;

    @Override
    public void onEvent(FlowableEvent flowableEvent) {
        System.out.println("---------------------创建任务onEvent-------------------------");
        // 当前节点任务实体,
        TaskEntity taskEntity = (TaskEntity) ((FlowableEntityEventImpl) flowableEvent).getEntity();
        String taskId = taskEntity.getId();

        Set<IdentityLink> candidates = taskEntity.getCandidates();
        Iterator<IdentityLink> iterator = candidates.iterator();
        StringBuffer buffer=new StringBuffer();
        while (iterator.hasNext()){
            IdentityLink next = iterator.next();
            String groupId = next.getGroupId();
            buffer.append(groupId+":");;
        }
        Map<String, Object> processVariables = taskEntity.getProcessVariables();
        Set<String> variableNames = taskEntity.getVariableNames();
        Iterator<String> iterator1 = variableNames.iterator();
        Object userOrgCode1 = taskEntity.getVariable("userOrgCode");
        buffer.append(","+userOrgCode1);
        String restUrl = address+"/performance/hontUser/hondlerMessage";
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("params",buffer.toString());
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        ThreadLocal<Map<String, Object>> toThreadLocal = FlowAbleInterceptor.toThreadLocal;
        Map<String, Object> stringObjectMap = toThreadLocal.get();
        headers.set("accessToken",stringObjectMap.get("accessToken").toString());
        //将请求头部和参数合成一个请求
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);
        //执行HTTP请求，将返回的结构使用ResultVO类格式化
        ResponseEntity<Result> resultResponseEntity = client.postForEntity(restUrl, requestEntity, Result.class, method);
       /*
       远程
       * */

        System.out.println("本地线程变量token:"+stringObjectMap.get("accessToken"));
        System.out.println("远程调用成功！");
        if(resultResponseEntity.getBody().getCode().equals("200")){
            logger.error("流程数据消息发送失败:"+taskEntity.getProcessInstanceId());
        }
    }

    @Override
    protected void taskCreated(FlowableEngineEntityEvent event) {
        System.out.println("---------------------创建任务-------------------------");
        if (event instanceof FlowableEntityEventImpl){
            //得到流程定义id
            String processDefinitionId = event.getProcessDefinitionId();
            //得到流程实例id
            String processInstanceId = event.getProcessInstanceId();
            FlowableEntityEventImpl eventImpl = (FlowableEntityEventImpl) event;
            //得到任务实例
            TaskEntity entity = (TaskEntity)eventImpl.getEntity();
            //1、授权

            //2、相邻节点自动跳过

            //3、发送消息
        }

    }


}
